package com.jz.community.basecomm.net.retrofit;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 适用Retrofit网络请求Observable(被监听者)
 *
 *
 */
public class HttpRxObservable {

    /**
     * 无管理生命周期,容易导致内存溢出
     */
    public static <T> Observable getObservable(Observable<T> apiObservable) {
        // showLog(request);
        Observable observable = apiObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .timeout(60, TimeUnit.SECONDS);
        return observable;
    }

    /**
     * 获取被监听者
     * 备注:网络请求Observable构建
     * data:网络请求参数
     * <h1>补充说明</h1>
     * 传入LifecycleProvider自动管理生命周期,避免内存溢出
     * 备注:需要继承RxActivity.../RxFragment...
     */
    public static <T> Observable getObservable(LifecycleProvider lifecycle, Observable<T> apiObservable) {
        //showLog(request);
        Observable observable;

        if (lifecycle != null) {
            //随生命周期自动管理.eg:onCreate(start)->onStop(end)
            observable = apiObservable
                    .compose(lifecycle.bindUntilEvent(ActivityEvent.PAUSE))//需要在这个位置添加
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .timeout(60, TimeUnit.SECONDS);
        } else {
            observable = getObservable(apiObservable);
        }
        return observable;
    }

    /**
     * 获取被监听者
     * 备注:网络请求Observable构建
     * data:网络请求参数
     * <h1>补充说明</h1>
     * 传入LifecycleProvider<ActivityEvent>手动管理生命周期,避免内存溢出
     * 备注:需要继承RxActivity,RxAppCompatActivity,RxFragmentActivity
     */
    public static <T> Observable getObservable(LifecycleProvider<ActivityEvent> lifecycle, Observable<T> apiObservable, ActivityEvent event) {
        Observable observable;
        if (lifecycle != null) {
            //手动管理移除监听生命周期.eg:ActivityEvent.STOP
            observable = apiObservable
                    .compose(lifecycle.bindUntilEvent(event))//需要在这个位置添加
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .timeout(60, TimeUnit.SECONDS);
        } else {
            observable = getObservable(apiObservable);
        }
        return observable;
    }

}
